package com.benshou.bsoa.common.quartz;

import com.benshou.bsoa.common.trace.TraceIdContext;
import com.benshou.bsoa.common.util.ApplicationContextProvider;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class QuartzJobWrapper implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        try {
            // 设置 TraceId
            TraceIdContext.ensureTraceIdExists();

            // 获取任务信息
            String beanName = context.getJobDetail().getJobDataMap().getString("beanName");
            String methodName = context.getJobDetail().getJobDataMap().getString("methodName");

            // 执行任务
            ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
            Object bean = applicationContext.getBean(Class.forName(beanName));
            Method method = bean.getClass().getMethod(methodName);
            method.invoke(bean);
        } catch (Exception e) {
            throw new RuntimeException("执行任务失败", e);
        }
    }
}